package org.daidai.abstrusewriting.homepage.top.fragment;


import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import org.daidai.abstrusewriting.R;
import org.daidai.abstrusewriting.fragments.BaseFragment;
import org.daidai.abstrusewriting.homepage.top.PlayActivity;
import org.daidai.abstrusewriting.homepage.top.adapters.ListItemDetailAdapter;
import org.daidai.abstrusewriting.homepage.top.model.RankingListDetail;
import org.daidai.abstrusewriting.homepage.top.service.TopService;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;
import rx.Observable;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * A simple {@link Fragment} subclass.
 */
public class TopListFragment extends BaseFragment implements AbsListView.OnScrollListener, SwipeRefreshLayout.OnRefreshListener, AdapterView.OnItemClickListener {

    private String title;
    private static final String TAG = "TopListFragment";
    private static List<RankingListDetail.ListItem> list;
    private ListItemDetailAdapter adapter;
    private String key;
    private ListView listView;
    private int pageId;
    private Retrofit retrofit;
    private boolean hasScroll;
    private SwipeRefreshLayout refreshLayout;

    public void setTitle(String title) {
        this.title = title;
    }

    public TopListFragment() {
        // Required empty public constructor
    }

    @Override
    public String getFragmentTitle() {
        return title;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getArguments() != null) {
            key = getArguments().getString("key");
            Log.d(TAG, "onCreate: " + key);
        }

        list = new ArrayList<>();

        Retrofit.Builder builder = new Retrofit.Builder();
        retrofit = builder.baseUrl("http://mobile.ximalaya.com/mobile/discovery/v2/rankingList/")
                .addCallAdapterFactory(RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io()))
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        pageId++;
        getData(pageId , 1);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_top_list, container, false);
        refreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.top_list_SwipeRefreshLayout);
        refreshLayout.setColorSchemeColors(Color.RED , Color.CYAN ,  Color.BLUE , Color.GREEN);
        refreshLayout.setOnRefreshListener(this);
        listView = (ListView) view.findViewById(R.id.top_list_listview);
        adapter = new ListItemDetailAdapter(getContext(), list);
        listView.setAdapter(adapter);
        listView.setOnScrollListener(this);
        listView.setOnItemClickListener(this);
        return view;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        switch (scrollState) {
            case SCROLL_STATE_IDLE://不滑动时
                if (view.getLastVisiblePosition() == (view.getCount() - 1)) {
                    getData(pageId , 2);
                }
                break;
            case SCROLL_STATE_FLING:
                hasScroll = true;
                break;
            case SCROLL_STATE_TOUCH_SCROLL:
                hasScroll = true;
                break;
        }
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        if (firstVisibleItem == 0) {
            View childAt = view.getChildAt(0);
            if (childAt != null && childAt.getTop() == 0) {
                if (hasScroll){

//                    Log.d(TAG, "onScroll: 到顶部");
                }
            }
        }
    }

    @Override
    public void onRefresh() {
        Log.d(TAG, "onRefresh: 刷新");
        getData(1 , 3);
        pageId = 1;
    }

    private void getData(final int page , final int state){
        Observable<RankingListDetail> observable = retrofit.create(TopService.class).getTopListDetail("android", key, page, 20, 2);
        observable.observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<RankingListDetail>() {
                    @Override
                    public void onCompleted() {
                        pageId ++;
                        if (state == 3){
                            refreshLayout.setRefreshing(false);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(RankingListDetail rankingListDetail) {
                        List<RankingListDetail.ListItem> lists = rankingListDetail.getList();
                        if (state != 2){
                            list.clear();
                        }
                        list.addAll(lists);
                        adapter.notifyDataSetChanged();
                    }
                });
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (list != null && list.size() >= position && list.size() != 0){

            RankingListDetail.ListItem listItem = list.get(position);
            Log.d(TAG, "onItemClick: " + position + listItem.getTitle());
            long uid = listItem.getUid();
            long trackId = listItem.getTrackId();
            Intent intent = new Intent(getContext(), PlayActivity.class);
            intent.putExtra("uid" , uid);
            intent.putExtra("trackId" , trackId);
            startActivity(intent);
        } else {
            Toast.makeText(getContext(), "未加载到数据", Toast.LENGTH_SHORT).show();
        }
    }
}
